/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: MyWebSocket
 * Author:   周宏硕
 * Date:     2018/11/6 10:08
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.htwx.websocket;

import com.htwx.entity.User;
import net.sf.json.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 周宏硕
 * @create 2018/11/6
 * @since 1.0.0
 */

@ServerEndpoint("/websocket/{userid}")
public class MyWebSocket {
    //记录当前连接数
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    private static Map<String, MyWebSocket> clients = new ConcurrentHashMap<String, MyWebSocket>();


    //    会话数据
    private String userid;

    private Session session;

    //处理报表
    private final  String  PROCESSREPORT="processReport";

    //报表维修完成
    private final  String  REPORTFINISH="reportFinish";

    //更新工厂信息
    private  final  String UPDATEFACTORY="updateFactory";

    //删除记录
    private  final  String DELETEREPORT="deleteReport";




    @OnOpen

    public void onOpen(@PathParam("userid") String userid, Session session) {
        this.session = session;
        this.userid = userid;
        JSONObject jsonObject = JSONObject.fromObject(userid);
        String user = jsonObject.getString("userid");
        String software = jsonObject.getString("softwaretype");

//        webSocketSet.add(this);
        clients.put(userid, this);


        addOnlineCount();           //在线数加
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
        System.out.println("software=" + software);
        System.out.println("userid=" + user);
    }

    /**
     * 连接关闭调用的方法
     */

    @OnClose

    public void onClose() {

//        webSocketSet.remove(this);  //从set中删除
        clients.remove(userid);
        subOnlineCount();           //在线数减1

        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());

    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */

    @OnMessage

    public void onMessage(String message, Session session) throws IOException {
        JSONObject jsonObject = JSONObject.fromObject(message);
        //解析当前用户id的json数据
        JSONObject jsoIdObject = JSONObject.fromObject(this.userid);

        //字符串解析数据
        String softwareType = jsonObject.getString("softwareType");
        String context = jsonObject.getString("content");
        String instructions=jsonObject.getString("instructions");
        String sendsocket = jsonObject.getString("socketId");
        String instruct=jsonObject.getString("instruct");

          //管理员或用户id
         String NowId=jsoIdObject.getString("userid");
        System.out.println("来自客户端的消息" + message);

        //判断类型用户还是管理员 User用户一对多  Manager管理员 一对一  ManagerToUser 一对多个用户
        if (softwareType.equals("Manager")||softwareType=="Manager") {

            if (sendsocket != null && sendsocket != "" && !sendsocket.equals("")) {
                System.out.println("发送的用户" + sendsocket);
                sendMessageTo("提示："+instructions + context, sendsocket.toString(),instruct);
            } else {
                System.out.println("socketId为null");
            }


        }else if(softwareType.equals("User")||softwareType=="User"){

            System.out.println("发送给管理员" + sendsocket);
             sendMessageToManager("提示："+instructions+ "" + context,softwareType,instruct);

        }else if(softwareType.equals("ManagerToUser")||softwareType=="ManagerToUser"){
            System.out.println("发送给所有用户");
            sendMessageToUserAll("提示："+instructions+ "" + context,softwareType,instruct);
        }

    }

    //发送给指定用户
    public void sendMessageTo(String message, String socketId,String instruct) throws IOException {

        JSONObject jsonObject = null;

        for (MyWebSocket item : clients.values()) {
            jsonObject = JSONObject.fromObject(item.userid);
            String userId = jsonObject.getString("userid");
            if (userId.equals(socketId))
                item.session.getAsyncRemote().sendText(message+","+instruct);
        }
    }

    //发给所有用户
    public void sendMessageToUserAll(String message, String socketId,String instruct) throws IOException {

        JSONObject jsonObject = null;

        for (MyWebSocket item : clients.values()) {
            //判断softwareType是否是发送给管理员
            jsonObject = JSONObject.fromObject(item.userid);
            String user_softwareTypes = jsonObject.getString("softwaretype");
            if (user_softwareTypes.equals("1"))
                item.session.getAsyncRemote().sendText(message+","+instruct);

        }
    }


    //发送给所有管理员
    public void sendMessageToManager(String message, String softwareType,String instruct) throws IOException {
        JSONObject jsonObject = null;
        for (MyWebSocket item : clients.values()) {
           //判断softwareType是否是发送给管理员
            jsonObject = JSONObject.fromObject(item.userid);
            String user_softwareTypes = jsonObject.getString("softwaretype");
            if (user_softwareTypes.equals("2"))
                item.session.getAsyncRemote().sendText(message);
        }
    }


    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */

    @OnError

    public void onError(Session session, Throwable error) {

        System.out.println("发生错误");

        error.printStackTrace();

    }


    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */

    public void sendMessage(String message) throws IOException {

        this.session.getBasicRemote().sendText(message);

    }


    public static synchronized int getOnlineCount() {

        return onlineCount;

    }


    public static synchronized void addOnlineCount() {

        MyWebSocket.onlineCount++;

    }


    public static synchronized void subOnlineCount() {

        MyWebSocket.onlineCount--;

    }


}
